# -*- coding: utf-8 -*-

from odoo import models, fields, api,_
import logging
_logger = logging.getLogger(__name__)
class card(models.Model):
    _name = "numpril.card"
   
    name = fields.Char(string="卡号", required=True)
    card_password = fields.Char(size=6,string="密码")
    card_balance = fields.Float(string="余额" )
    
    # client_recharge = fields.One2many('numpril.recharge','recharge_client',ondelate='set null',string="充值记录")
    card_consump = fields.One2many('numpril.consumption','consump_id',ondelate='set null',string="消费记录")
    card_recharge = fields.One2many('numpril.recharge','recharge_id',ondelate='set null',string="充值记录")
    
    
    @api.model
    def passw_comfirm(self,arg1,arg2):
        domain=[('name','=',arg1)]
        result = self.env['numpril.card'].search(domain)
        record = False
        _logger.info("password:%s",arg1)
        if result.card_password == arg2:
            record = True
        return record

            

    # @api.constrains('name')
    # def __check_name(self):
    #     cards = self.search(['name','=',self.name])
    #     if len(cards)>1:
    #         raise except_orm(u'错误',u'已经存在%s的名字的卡号'%self.name)

    # _sql_constraints=[(
    #     'cons_tech_demo_name','UNIQUE(name)',u'已存在！'
    # )]
class consumption(models.Model):
    _name = 'numpril.consumption'
   

    # consumpt = fields.Many2one('numpril.client',u'client')
    consump_amount = fields.Float(string="消费金额",required=True)
    consump_id = fields.Many2one('numpril.card',string="卡号")
    # comsump_time = fields.Date(compute='_compute_now',string="消费时间")
    comsump_time = fields.Datetime(string="消费时间")
    consump_merchant = fields.Many2one('res.users',string="商户")

    # @api.one
    # def _compute_now(self):
        # self.comsump_time = fields.Datetime.now()

    @api.constrains('consump_amount')
    def _check_consumpamount(self):
        record = self.with_context()
        if record['consump_id']['card_balance'] < self.consump_amount:
            raise ValueError("你的卡余额不足！" )
            print "***************************************"
            print record['consump_id']['card_balance']
    
    @api.model
    def create(self,vals):
        record = super(consumption,self).create(vals)
        record['consump_id']['card_balance'] = record['consump_id']['card_balance']-record['consump_amount']
        return record

    @api.multi
    def unlink(self):
        _logger.info("total:%s",self['consump_id']['card_balance'])
        _logger.info("total:%s",self['consump_amount'])
        self['consump_id']['card_balance'] = self['consump_id']['card_balance']+self['consump_amount']
        return super(consumption,self).unlink()
    
    
    @api.model
    def add_comsumption(self,arg1,arg2):
        _logger.info("total:%s",arg1)

        domain=[('name','=',arg1)]
        record = "123456"
        time = fields.Datetime.now()
        result = self.env['numpril.card'].search(domain)
        pass_result = [0,0]
        #user = self.env['res.users'].sudo().search([])
        _logger.info("total:%s",result.card_balance)
        #_logger.info(len(result))
        if len(result) == 1:
            consumption = self.env['numpril.consumption'].sudo().search([])
            _logger.info("manager:%s",self.env.user.name)
            consumption.create({'consump_amount':arg2,'comsump_time':time,'consump_id':result.id,'consump_merchant':self.env.user.id})
            _logger.info("total:%s",result.card_balance)
        else:
            raise ValueError("该卡异常！")
        _logger.info("total:%s",arg2)
        pass_result[0] = self.env.user.name
        pass_result[1] = result.card_balance
        return pass_result

    
    
            
        
        
    

class merchant(models.Model):
    _inherit="res.users"

    name = fields.Char(string="商户")
    # name = fields.One2many('numpril.consumption','consump_merchant',string="商户")
    merch_consump = fields.One2many('numpril.consumption','consump_merchant',string="消费记录")

    # name = fields.Char(default=lambda self:self.env.user.name,readonly="1")
    # merch_consump = fields.One2many('numpril.consumption','consump_merchant',ondelate='set null',string="消费记录")



class recharge(models.Model):
    _name = 'numpril.recharge'

    recharge_id = fields.Many2one('numpril.card',string="卡号")
    # recharge_client = fields.One2many('numpril.client',string="客户")
    recharge_number = fields.Float(string="充值金额")
    recharge_time = fields.Datetime(string="充值时间")
 
    @api.model
    def create(self,vals):
        record = super(recharge,self).create(vals)
        record['recharge_id']['card_balance'] = record['recharge_id']['card_balance']+record['recharge_number']
        return record

    @api.model
    def add_recharge(self,arg1,arg2):
        _logger.info("total:%s",arg1)

        domain=[('name','=',arg1)]
        record = "123456"
        time = fields.Datetime.now()
        result = self.env['numpril.card'].search(domain)
        pass_result = [0,0]
        user = self.env['res.users'].sudo().search([])
        _logger.info("total:%s",result.card_balance)
        #_logger.info(len(result))
        if len(result) == 1:
            recharge = self.env['numpril.recharge'].sudo().search([])
            
            recharge.create({'recharge_number':arg2,'recharge_time':time,'recharge_id':result.id})
            _logger.info("total:%s",result.card_balance)
        else:
            raise ValueError("该卡异常！")
        _logger.info("total:%s",arg2)
        pass_result[0] = self.env.user.name
        pass_result[1] = result.card_balance
        return pass_result


class account(models.Model):
    _name = 'numpril.account'

    account_merchant = fields.Many2one('res.users',string='商户',required =True)
    account_amount = fields.Float(string='结帐金额',compute = "_compute_amount")
    account_start = fields.Date(string="开始时间" )
    account_end = fields.Date(string="结束时间")
    account_confirm = fields.Boolean(string="是否对账", default=False)


    # @api.one
    # def sum(self):
    #     _logger.info("account_merchant:%s",self.account_merchant.id)
    #     # _logger.info("account_start:%s",self.account_start)
    #     domain = []
    #     domain += ['&', ('consump_merchant','=',self.account_merchant.id)]
    #     domain += ['&', ('comsump_time', '>=',self.account_start +' 00:00:00'),('comsump_time', '<=', self.account_end +' 23:59:59')]
    #     # best_index = -1
    #     _logger.info("domain:%s",domain)
    #     res = self.env['numpril.consumption']
    #     total = 0
    #     for rec in res.search(domain):
    #         _logger.info("consump_amount:%s",rec.consump_amount)
    #         total += rec.consump_amount
    #     _logger.info("total:%s",total)
    #     self.account_amount = total

    @api.one
    @api.depends('account_start','account_end')
    def _compute_amount(self):
        _logger.info("account_merchant:%s",self.account_merchant.id)
        # _logger.info("account_start:%s",self.account_start)
        domain = []
        domain += ['&', ('consump_merchant','=',self.account_merchant.id)]
        domain += ['&', ('comsump_time', '>=',self.account_start +' 00:00:00'),('comsump_time', '<=', self.account_end +' 23:59:59')]
        # best_index = -1
        _logger.info("domain:%s",domain)
        res = self.env['numpril.consumption']
        total = 0
        for rec in res.search(domain):
            _logger.info("consump_amount:%s",rec.consump_amount)
            total += rec.consump_amount
        _logger.info("total:%s",total)
        self.account_amount = total

    
    @api.constrains('account_start','account_end')
    def _check_account(self):
        if self.account_start > self.account_end:
            raise ValueError("时间错误！")

            